import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))# 双括号用于创建一个元组。单括号只是一个元组，
# pygame.display.set_mode()函数需要一个包含两个元素的元组作为参数,需要使用双括号将这两个变量括起来，以创建一个元组。
score = 0
# 定义一个变量来存储登录状态
is_logged_in = False
#在pygame的游戏窗口中绘制文本
def draw_text(text, x, y, font_size, color):#text（要绘制的文本内容），
    font = pygame.font.Font(None, font_size)
    text_surface = font.render(text, True, color)
    #使用font.render(text, True, color)将文本渲染为一个Surface对象，其中True表示启用抗锯齿，color表示文本颜色。
    text_rect = text_surface.get_rect()# 使用text_surface.get_rect()获取文本Surface对象的矩形区域。
    text_rect.center = (x, y)
    screen.blit(text_surface, text_rect)#将文本Surface对象绘制到游戏窗口上。


# 加载背景图片
background_image = pygame.image.load(r'C:\Users\lenovo\OneDrive\Pictures\Camera Roll\贪吃蛇背景3.jpg')
# 加载蛇头图片[动画表情]
snake_head_image = pygame.image.load('无标题.png')
snake_head_image.set_colorkey((255, 255, 255))#设置图像透明度的函数
#加载蛇身图片
snake_tail_image = pygame.image.load('蛇身.png')
snake_tail_image.set_colorkey((255, 255, 255))
# 设置游戏速度
clock = pygame.time.Clock()
speed = 5  # 设置帧率为10
# 定义蛇和食物的大小
block_size = 20

# 定义颜色
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PINK = (255, 192, 203)
# 蛇的初始位置
snake_pos = [[100, 100], [80, 100], [60, 100]]

# 食物的初始位置
food_pos = [300, 300]

# 加载背景音乐和吃食物的音效
pygame.mixer.init()
pygame.mixer.music.load("背景音乐.mp3")
pygame.mixer.music.play(-1)  # -1表示循环播放
eat_sound = pygame.mixer.Sound("音效.wav")

def draw_snake(snake_pos):
    for i, pos in enumerate(snake_pos):
        if i == 0:
            # 计算旋转角度
            if direction == 'right':
                angle = 0
            elif direction == 'left':
                angle = 180
            elif direction == 'up':
                angle = 90
            elif direction == 'down':
                angle = 270
            # 旋转蛇头图片
            rotated_head_image = pygame.transform.rotate(snake_head_image, angle)
            screen.blit(rotated_head_image, (pos[0], pos[1]))  # 使用旋转后的蛇头图片
        else:
            screen.blit(snake_tail_image, (pos[0], pos[1]))  # 使用蛇身图片

def move_snake(snake_pos, direction):
    # 保存蛇头当前坐标
    head_x, head_y = snake_pos[0]
    # 根据方向更新蛇头坐标
    if direction == 'right':
        head_x += block_size
    elif direction == 'left':
        head_x -= block_size
    elif direction == 'up':
        head_y -= block_size
    elif direction == 'down':
        head_y += block_size
    # 将更新后的蛇头坐标插入列表开头
    snake_pos[0] = [head_x, head_y]  # 直接更新蛇头坐标


def check_collision(snake_pos, food_pos):
    if snake_pos[0] == food_pos:

        # 当蛇吃到食物时，增长蛇身
        snake_pos.append(snake_pos[-2])  # 在蛇的当前位置列表末尾添加一个新的蛇身部分
        return True
    return False


def draw_food(food_pos):
    pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], block_size, block_size))

#蛇身移动函数
def move_snake(snake_pos, direction):
    x, y = snake_pos[0]
    if direction == 'right':
        x += block_size
    elif direction == 'left':
        x -= block_size
    elif direction == 'up':
        y -= block_size
    elif direction == 'down':
        y += block_size
    #控制蛇的移动
    snake_pos.insert(0, [x, y])#更新蛇头的位置
    snake_pos.pop()#删除蛇尾的位置


def check_collision(snake_pos, food_pos):
    if snake_pos[0] == food_pos:
        return True
    return False


def generate_food(snake_pos):
    while True:
        x = random.randrange(0, screen_width, block_size)
        y = random.randrange(0, screen_height, block_size)
        if [x, y] not in snake_pos:
            return [x, y]

def check_game_over(snake_pos):
    x, y = snake_pos[0]
    if x < 0 or x >= screen_width or y < 0 or y >= screen_height or snake_pos[0] in snake_pos[1:]:
        return True
    return False
def draw_score(score, x, y, font_size, color):
    font = pygame.font.Font('1.ttf', 20)
    score_surface = font.render(str(score), True, color)
    score_rect = score_surface.get_rect()
    score_rect.topleft = (x, y)
    screen.blit(score_surface, score_rect)
def draw_snake(snake_pos):
    for i, pos in enumerate(snake_pos):
        if i == 0:
            # 计算旋转角度
            if direction == 'right':
                angle = 0
            elif direction == 'left':
                angle = 180
            elif direction == 'up':
                angle = 90
            elif direction == 'down':
                angle = 270
            # 旋转蛇头图片
            rotated_head_image = pygame.transform.rotate(snake_head_image, angle)
            screen.blit(rotated_head_image, (pos[0], pos[1]))  # 使用旋转后的蛇头图片
        else:
            screen.blit(snake_tail_image, (pos[0], pos[1]))  # 使用蛇身图片
direction = 'right'


# 定义登录界面函数
def show_login_screen():
    global is_logged_in
    login_screen_background = pygame.Surface((screen_width, screen_height))
    login_screen_background.fill((135, 206, 250))  # 浅天空蓝色背景

    username ="zrr"
    password ="123"

    font = pygame.font.Font(None, 32)
    while not is_logged_in:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if username == "zrr" and password == "123":  # 这里填入正确的用户名和密码
                        is_logged_in = True
                    else:
                        username = ""
                        password = ""
                if event.key == pygame.K_BACKSPACE:
                    if username:
                        username = username[:-1]
                    if password:
                        password = password[:-1]
                else:
                    if len(username) < 15:  # 限制用户名长度
                        username += event.unicode
                    if len(password) < 15:  # 限制密码长度
                        password += "*"

        screen.fill((0, 0, 0))  # 清屏
        screen.blit(login_screen_background, (0, 0))

        # 绘制登录界面文本
        title_text = font.render("Login", True, (0, 0, 0))
        title_rect = title_text.get_rect(center=(screen_width // 2, 50))
        screen.blit(title_text, title_rect)

        # 绘制用户名和密码输入框
        username_text = font.render("Username:", True, (0, 0, 0))
        username_rect = username_text.get_rect(center=(screen_width // 2, 150))
        screen.blit(username_text, username_rect)

        password_text = font.render("Password:", True, (0, 0, 0))
        password_rect = password_text.get_rect(center=(screen_width // 2, 200))
        screen.blit(password_text, password_rect)

        # 绘制用户输入的用户名和密码
        username_input = font.render(username, True, (0, 0, 0))
        username_input_rect = username_input.get_rect(center=(screen_width // 2, 175))
        screen.blit(username_input, username_input_rect)

        password_input = font.render(password, True, (0, 0, 0))
        password_input_rect = password_input.get_rect(center=(screen_width // 2, 225))
        screen.blit(password_input, password_input_rect)

        pygame.display.flip()

# 主循环开始前调用登录界面
show_login_screen()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and direction != 'down':
                direction = 'up'
            elif event.key == pygame.K_DOWN and direction != 'up':
                direction = 'down'
            elif event.key == pygame.K_LEFT and direction != 'right':
                direction = 'left'
            elif event.key == pygame.K_RIGHT and direction != 'left':
                direction = 'right'

    move_snake(snake_pos, direction)

    if check_collision(snake_pos, food_pos):
        food_pos = generate_food(snake_pos)
        snake_pos.append(snake_pos[-1])
        score+=10  # 每次吃到食物，分数增加10
        eat_sound.play()
        # 播放吃食物的音效
        game_paused = True

    if check_game_over(snake_pos):
        break

    screen.blit(background_image, (0, 0))  # 绘制背景图片
    draw_snake(snake_pos)
    draw_food(food_pos)
    draw_score(score, 10, 10, 20, WHITE)  # 绘制分数
    pygame.display.flip()
    clock.tick(speed)  # 设置帧率为10


pygame.quit()
